package cn.djx.springsecurity.config;

import cn.djx.springsecurity.filter.AuthenticationTokenFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private AuthenticationTokenFilter authenticationTokenFilter;

    @Resource
    private AccessDeniedHandler accessDeniedHandler;
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;





    @Bean
    // 返回一个 BCryptPasswordEncoder 实例作为 PasswordEncode
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                // 允许匿名访问 /users/login 和 /users/register
                .requestMatchers("/users/login").anonymous()
                .requestMatchers("/users/register").permitAll()
                .requestMatchers("/users/test").hasAuthority("system:test:list")
                // 其他请求需要身份验证
                .anyRequest().authenticated()
        ).csrf(
                // 禁用CSRF防护 不然post无法访问
                csrf -> csrf.disable()
        ).sessionManagement(
                // 基于token，所以不需要session
                session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ).exceptionHandling(
                // 异常处理
                exception -> exception.accessDeniedHandler(accessDeniedHandler)
                        .authenticationEntryPoint(authenticationEntryPoint)
        ).headers(
                // 禁用HTTP响应标头
                headers -> headers.cacheControl(
                        cacheControl -> cacheControl.disable()
                )

        )
                // 自定义的 登录过滤器
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    // 返回身份验证管理器的 Bean
    public AuthenticationManager authenticationManager() {
        // 创建 DaoAuthenticationProvider 实例
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        // 设置用户详细信息服务
        authenticationProvider.setUserDetailsService(userDetailsService);
        // 设置密码加密器
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        // 返回新的 ProviderManager 实例，将 DaoAuthenticationProvider 作为身份验证提供者
        return new ProviderManager(authenticationProvider);
    }

}
